//
//  AFNHTTPSRequest.m
//  EquesCat
//
//  Created by Chun Hung Cheung on 2024/12/17.
//

#import "AFNHTTPSRequest.h"
@implementation AFNHTTPSRequest
+ (void)httpsRequestWithUrl:(NSURL *)url errorHint:(void(^)(id errorData))errorHint result:(void(^)(id data))block
{
     AFHTTPSessionManager *manager =  [self managerwithbasicurl:url];
     NSLog(@"get 请求json数据URL接口---%@",url);
    if (url) {
        NSString *urlstr = [url absoluteString];
       [manager GET:urlstr parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
           NSLog(@"request url == %@  \nget response message--->%@ \n",url,[Tooles getChinaWordAndJosn:responseObject]);
           block(responseObject);
           
       } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
           NSLog(@"get request error--->%@",error);
           errorHint(error);
       }];
    } // 13823166314
    
    
}

+ (void)httpsRequestWithUrl:(NSURL *)url errorHint:(void(^)(id errorData))errorHint result:(void(^)(id data))block andHeader:(NSDictionary*)value isPost:(BOOL)isPost
{
     AFHTTPSessionManager *manager =  [self managerwithbasicurl:url];
     NSLog(@"get 请求json数据URL接口---%@",url);
     NSString *urlstr = [url absoluteString];

    if (urlstr) {
        if (isPost) {
            [manager POST:urlstr parameters:nil headers:value progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSLog(@"request url == %@  \nget response message--->%@ \n",urlstr,[Tooles getChinaWordAndJosn:responseObject]);
                
                block(responseObject);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSLog(@"post 请求json数据 error--->%@",error);
                errorHint(error);
            }];
        }else{
            [manager GET:urlstr parameters:nil headers:value progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSLog(@"request url == %@\n  response message--->%@ \n",urlstr,[Tooles getChinaWordAndJosn:responseObject]);
                
                block(responseObject);
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSLog(@"get 请求json数据 error--->%@",error);
                errorHint(error);
            }];
            
        }
        
    }
}

+ (void)httpsRequestnewWithUrl:(NSURL *)url errorHint:(void(^)(id errorData))errorHint result:(void(^)(id data))block
{
    AFHTTPSessionManager *manager =  [self managerwithbasicurl:nil];
    
    NSString *urlstr = [url absoluteString];
    NSLog(@"单独请求服务器证书URL接口---%@",url);
    [manager GET:urlstr parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"responseObject--->%@",[Tooles getChinaWordAndJosn:responseObject]);
        block(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"单独请求服务器证书URL接口 error--->%@",error);
        errorHint(error);
    }];
}

// 返回的数据为二进制数据
+ (void)httpsRequestWithUrlDownloadImage:(NSURL *)url errorHint:(void(^)(id errorData))errorHint result:(void(^)(id data))block
{
     NSLog(@"请求图片下载的URL接口--->%@",url);
     AFHTTPSessionManager *manager =  [self managerwithbasicurl:url];
     //响应内容序列化为二进制
     manager.responseSerializer = [AFHTTPResponseSerializer serializer];
     NSString *urlstr = [url absoluteString];
    [manager GET:urlstr parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
        block(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        errorHint(error);
    }];
}


+ (void)bindLockPostWiFIWithUrl:(NSURL *)url errorHint:(void(^)(id errorData))errorHint deleteDic:(id)deleteDic result:(void(^)(id data))block
{
     AFHTTPSessionManager *manager = [self managerwithbasicurl:url];
     manager.requestSerializer = [AFJSONRequestSerializer serializer];
     NSString *urlstr = [url absoluteString];
    [manager POST:urlstr parameters:deleteDic headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        block(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"post json数据URL接口 error-->%@", error);
        errorHint(error);
    }];
}

+ (void)httpsDeleteRequestWithUrl:(NSURL *)url errorHint:(void(^)(id errorData))errorHint deleteDic:(id)deleteDic result:(void(^)(id data))block
{
    AFHTTPSessionManager *manager = [self managerwithbasicurl:url];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
     NSString *urlstr = [url absoluteString];
     NSLog(@"delete json数据URL接口-->%@",url);
     NSLog(@"delete json数据-->%@",deleteDic);
    [manager DELETE:urlstr parameters:deleteDic headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"responseObject--->%@",[Tooles getChinaWordAndJosn:responseObject]);
        block(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         NSLog(@"delete json数据URL接口 error-->%@", error);
               errorHint(error);
    }];
}



+ (void)httpsPostRequestWithUrl:(NSURL *)url errorHint:(void(^)(id errorData))errorHint deleteDic:(id)deleteDic isFavorite:(BOOL)isFavorite result:(void(^)(id data))block
{
    AFHTTPSessionManager *manager = [self managerwithbasicurl:url];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    NSString *urlstr = [url absoluteString];
    NSLog(@"post json数据URL接口-->%@",url);
    NSLog(@"post json数据-->%@",deleteDic);
    if (url) {
        
        if (deleteDic) {
            if (isFavorite) {
                
                [manager POST:urlstr parameters:deleteDic headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    NSLog(@"responseObject--->%@",[Tooles getChinaWordAndJosn:responseObject]);
                    block(responseObject);
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    NSLog(@"post json数据URL接口 error-->%@", error);
                    errorHint(error);
                }];
            }else{
                NSArray *array = @[deleteDic];
                [manager POST:urlstr parameters:array headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    NSLog(@"responseObject--->%@",[Tooles getChinaWordAndJosn:responseObject]);
                    block(responseObject);
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    NSLog(@"post json数据URL接口 error-->%@", error);
                    errorHint(error);
                }];
            }
        }else{
            [manager POST:urlstr parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSLog(@"responseObject--->%@",[Tooles getChinaWordAndJosn:responseObject]);
                block(responseObject);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSLog(@"post json数据URL接口 error-->%@", error);
                errorHint(error);
            }];
        }
    }
}

// 下载报警图片等信息
+ (void)httpsRequestDownloadTaskWithUrl:(NSURL *)url destinatonPath:(NSString*)downLoadPath  progross:(void(^)(float progrossFloat))progross result:(void(^)(id data))block
{
    NSLog(@"下载文件的接口-->%@",url);
    if (url) {
        AFHTTPSessionManager *manager = [self managerwithbasicurl:url];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        NSURLRequest *request1 = [NSURLRequest requestWithURL:url];
        //下载文件
        /* 第一个参数:请求对象
          第二个参数:progress 进度回调
          第三个参数:destination 回调(目标位置) 有返回值
            targetPath:临时文件路径 response:响应头信息
          第四个参数:completionHandler 下载完成后的回调 filePath:最终的文件路径 */
        NSURLSessionDownloadTask *download = [manager downloadTaskWithRequest:request1 progress:^(NSProgress * _Nonnull downloadProgress) {
            //下载进度
            progross(1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
            
        } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
            //保存的文件路径
            return [NSURL fileURLWithPath:downLoadPath];
        } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
            NSLog(@"filePath - %@",filePath);
            block(error);
        }];
        
        //执行Task
        [download resume];
    }
}

//上传日志或头像或人脸操作时上传的图片资源

+ (void)httpsUploadDocumentWithUrl:(NSURL*)url parameters:(id)parameters documentData:(NSData*)data name:(NSString*)name fileName:(NSString*)filename mimeType:(NSString*)mimeType errorHint:(void(^)(id errorData))errorHint result:(void(^)(id data))block
{
    
     NSLog(@"上传日志或头像或人脸操作时上传的图片资源接口---%@",url);
     AFHTTPSessionManager *manger = [self managerwithbasicurl:url];
 
    [manger POST:[url absoluteString] parameters:parameters headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        if (data) {
            [formData appendPartWithFileData:data name:name fileName:filename mimeType:mimeType];
        }
    
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"responseObject--->%@",[Tooles getChinaWordAndJosn:responseObject]);
        block(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        errorHint(error);
    }];
}





+ (AFHTTPSessionManager *)managerwithbasicurl:(NSURL*)url {
 
    AFHTTPSessionManager *manager;
//    if (url) {
////         manager = [[AFHTTPSessionManager manager] initWithBaseURL:url];
////        [manager setSecurityPolicy:[self customSecurityPolicy]];
//           manager = [AFHTTPSessionManager manager];
// }else{
    manager = [AFHTTPSessionManager manager];
// }
//    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
//    securityPolicy.allowInvalidCertificates = NO;
//    securityPolicy.validatesDomainName = NO;
//    manager.securityPolicy = securityPolicy;
  
    //默认解析模式
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    if ([[url absoluteString] isEqualToString:@"http://10.0.0.1/save.htm"]) {
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    }else{
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
    }
    //配置请求序列化
    AFJSONResponseSerializer *serializer = [AFJSONResponseSerializer serializer];
    
    [serializer setRemovesKeysWithNullValues:YES];
    manager.requestSerializer.stringEncoding = NSUTF8StringEncoding;
    
    manager.requestSerializer.timeoutInterval = 30;
    //配置响应序列化
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[@"application/json",
                                                                              @"text/html",
                                                                              @"text/json",
                                                                              @"text/plain",
                                                                              @"text/javascript",
                                                                              @"text/xml",
                                                                              @"image/*",
                                                                              @"application/octet-stream",
                                                                              @"application/zip"]];
    return manager;
}



+ (AFSecurityPolicy*)customSecurityPolicy{
    //先导入证书

    // AFSSLPinningModeCertificate 使用证书验证模式
       AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    // allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
    // 如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    
    //validatesDomainName 是否需要验证域名，默认为YES；
    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；
    //如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
    //如置为NO，建议自己添加对应域名的校验逻辑。
    securityPolicy.validatesDomainName = YES;
    
    NSMutableSet *cerdataSet = [NSMutableSet set];
    NSArray *array =  [[NSUserDefaults standardUserDefaults] objectForKey:@"cerArray"];
    for (NSString  *base64Encoded in array) {
        NSData *nsdataFromBase64String = [[NSData alloc]initWithBase64EncodedString:base64Encoded options:0];
        if (![cerdataSet containsObject:nsdataFromBase64String]) {

            [cerdataSet addObject:nsdataFromBase64String];
        }
    }
    
    securityPolicy.pinnedCertificates = cerdataSet;
    
    return securityPolicy;
}



+ (void)httpsVM6PostRequestWithUrl:(NSURL *)url errorHint:(void(^)(id errorData))errorHint deleteDic:(id)deleteDic isFavorite:(BOOL)isFavorite result:(void(^)(id data))block value:(NSString*)value
{
    AFHTTPSessionManager *manager = [self managerwithbasicurl:url];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];

    [manager.requestSerializer setValue:value forHTTPHeaderField:@"Authorization"];
    
    // 为单个请求设置请求头
//    NSDictionary *headers = @{
//        @"Content-Type": @"application/json",
//        @"Authorization": value
//    };
//  NSMutableDictionary *dict = [NSMutableDictionary dictionary];
//  [dict setValue:value forKey:@"Authorization"];
    NSString *urlstr = [url absoluteString];
    NSLog(@"post json数据URL接口-->%@",url);
    NSLog(@"post json数据-->%@",deleteDic);
    if (url) {
        [manager POST:urlstr parameters:@[deleteDic] headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"responseObject--->%@",[Tooles getChinaWordAndJosn:responseObject]);
            block(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            
               // 获取响应头
                NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
                NSDictionary *headers = [response allHeaderFields];
                NSLog(@"Response headers: %@", headers);
            
            
            errorHint(error);
        }];
    }
}
@end
